package inet.app.vod.activity.fun;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.adapter.FunAdapter;
import inet.app.vod.config.AppConstants;
import inet.app.vod.db.DaoFactory;
import inet.app.vod.db.DaoFun;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.CategoryModel;
import inet.app.vod.object.FunModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.widget.MyToast;

public class IFunCategoryActivity extends BaseActivity {

	private PullToRefreshListView mPullView;
	private ListView mListView;
	
	private DaoFun mDaoFun;
	private CategoryModel category;
	private FunAdapter mAdapter;
	private List<FunModel> mFunModels = new ArrayList<FunModel>();
	private int page = AppConstants.START_PAGE;

	OnRefreshListener2<ListView> onRefresh = new OnRefreshListener2<ListView>() {

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			requestListItem();
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			requestListItem();
		}
	};

	/*
	 * Click listView iFun to iFun detail
	 */
	AdapterView.OnItemClickListener funListviewListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			FunModel fun = mFunModels.get(position - 1);
			Bundle bundle = new Bundle();
			bundle.putSerializable("fun", fun);
			LaunchIntent.start(IFunCategoryActivity.this,
					IFunDetailActivity.class, bundle);
		}
	};

	private void initModels() {

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			category = (CategoryModel) bundle.getSerializable("category");
		}
		if (category == null) {
			MyToast.show(this, "Không tìm thấy chuyên mục này");
			finish();
			return;
		}
		mDaoFun = DaoFactory.getInstance(getApplicationContext()).getDaoFun();
	}

	private void initViews() {
		mPullView = (PullToRefreshListView) findViewById(R.id.ifun_listview);
		mPullView.setPullLabel(getString(R.string.keo_de_tai_them));
		mPullView.setRefreshingLabel(getString(R.string.dang_tai));
		mPullView.setReleaseLabel(getString(R.string.tha_de_bat_dau_tai));
		mPullView.setOnRefreshListener(onRefresh);
		mListView = mPullView.getRefreshableView();
		mListView.setOnItemClickListener(funListviewListener);
		setTitle(AppConstants.NAME_IFUN);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ifun);
		initUIBase();
		initModels();
		initViews();
		requestListItem();
	}

	private void requestListItem() {
		VolleyClient.requestItems(AppConstants.ID_IFUN, category.getRemoteId(),
				AppConstants.getPageSize(this), page, new VolleyListener(this) {

					@Override
					public void onSuccess(String response) {
						Log.d("success request" + response);
						ResultJsonModel jResult = Parse.parseFunList(response);
						if (jResult == null) {
							// error parser
							MyUtil.showDialog("Lỗi server",
									IFunCategoryActivity.this);
						} else if (jResult.hasError()) {
							// error register
							String error = jResult.getError();
							MyUtil.showDialog(error, IFunCategoryActivity.this);
						} else {
							// save categories to database
							mPullView.onRefreshComplete();
							List<FunModel> funs = (List<FunModel>) jResult
									.getResult();
							if (funs == null || funs.size() == 0) {
								MyToast.show(IFunCategoryActivity.this,
										"Đã tải hết dữ liệu");
								return;
							}
							if (page == 1) {
								mFunModels = funs;
							} else {
								mFunModels.addAll(funs);
							}
							showListFuns();
							page++;
							saveListFunsToDB(funs);
						}
					}

					@Override
					public void onStart() {
						Log.d("start request");
						showLoading(true);
					}

					@Override
					public void onFinish() {
						Log.d("finish request");
						showLoading(false);
					}

					@Override
					public void onError(VolleyError error) {
						MyUtil.showDialog("Lỗi server (" + error.getMessage()
								+ ")", IFunCategoryActivity.this);
					}
				});
	}

	private void saveListFunsToDB(List<FunModel> funs) {
		if (funs != null && funs.size() != 0) {
			mDaoFun.insertCollection(funs);
		}
	}

	private void showListFuns() {
		if (page == 1) {
			mAdapter = new FunAdapter(this, 0, mFunModels);
			mListView.setAdapter(mAdapter);
		} else {
			mAdapter.notifyDataSetChanged();
		}
		int newFirstPos = (page - 1) * AppConstants.getPageSize(this);
		if (android.os.Build.VERSION.SDK_INT > 10) {
			mListView.smoothScrollToPositionFromTop(newFirstPos + 1, 0);
		} else {
			mListView.smoothScrollToPosition(newFirstPos + 1);
		}
	}

	@Override
	public void setTagMenu() {
		mTagMenu = AppConstants.MENU_IFUN;
	}

}
